<!-- 通用订购作业：蹇泽阳 -->
<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <Find :OriginalFilter="{ static: true }" :formList="formList2" @findClicked="findClicked2" :searchImg="false" />
    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <div class="flex AIC">
          <h1 class="f16">通用材料订购明细</h1>
          <AddOne :tableHeader="tableHeader" :tableData="tableData" @Save="Save2" @AddHandle="AddHandle2" />
          <!-- <JDialog :tableHeader="JTableHeader" :width="73" @confirm="confirm" :unAdd="true" :unEdit="true" :unSub="true" /> -->
        </div>
        <JTable
          :outTableHeight="90"
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :isLoading="isLoading"
          @selectList="selectList1"
          @currentRow="clickRow"
        />
      </el-card>
    </div>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
    </el-card>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import router from '@/router'
import fileRequest from '@/utils/fileRequest'
import { formateData } from '@/plugins/mixinJ'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'GeneralOrder'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import Find from '@/components/Find/index.vue'
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { onMounted, watch } from 'vue'
const dialogTableVisible2 = ref(false)
// 分页器
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入订购单号',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '厂商代码 厂商名称',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料颜色',
    inputValue: ''
  },
  {
    dateLabel: '订购日期',
    dateValue: ''
  },
  {
    type: 'checkbox',
    checkboxLabel: '未下单',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '已下单',
    checked: false
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '查询',
    bgColor: '#1890FF'
  }
]) as any
const formList2 = ref([
  {
    type: 'button',
    checkboxLabel: '分类辅助生成'
  },
  {
    type: 'button',
    checkboxLabel: '生成物料编码'
  },
  {
    type: 'button',
    checkboxLabel: '置空物料编码'
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '厂商代码 厂商名称',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'dateSingle',
    dateLabel: '交期',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '形成订购单'
  },
  {
    type: 'button',
    checkboxLabel: '导出订购单'
  },
  {
    type: 'button',
    checkboxLabel: '置空订购信息'
  },
  {
    type: 'button',
    checkboxLabel: '打勾记录删除',
    bgColor: 'red'
  },
  {
    type: 'button',
    checkboxLabel: '>> 查询订购资料'
  }
])
const mtlNameOptions = ref([]) as any
const categoryNameOptions = ref([]) as any
const tableHeader = ref([
  {
    type: 'select',
    label: '类型',
    prop: 'purType',
    width: '80',
    options: [
      {
        value: '通用',
        label: '通用'
      }
    ]
  },
  {
    change: true,
    label: '订购单号',
    prop: 'purNo',
    width: '120'
  },
  {
    change: true,
    type: 'dateSingle',
    label: '订购日期',
    prop: 'purDate',
    width: 100
  },
  {
    type: 'select',
    label: '分类名称',
    prop: 'typeName',
    width: 80,
    options: categoryNameOptions.value
  },
  {
    change: true,
    label: '物料编码',
    prop: 'mtlNo',
    width: '100'
  },
  {
    label: '材料颜色',
    prop: 'mtlColor',
    width: '90'
  },
  {
    start: true,
    label: '材料名称',
    prop: 'mtlName',
    width: '300'
  },
  {
    type: 'select',
    label: '规格',
    prop: 'mtlSpec',
    options: [],
    width: '90'
  },
  {
    type: 'select',
    label: '单位',
    options: [],
    prop: 'mtlUnit',
    width: '90'
  },
  {
    label: '订购数量',
    prop: 'purQty',
    width: '90'
  },
  {
    change: true,
    label: '单价',
    prop: 'price',
    width: '90'
  },
  {
    change: true,
    label: '厂商',
    prop: 'vendorNo',
    width: '90'
  },
  {
    change: true,
    type: 'dateSingle',
    label: '交期',
    prop: 'deliveryDate',
    width: 120
  },
  {
    label: '备注',
    prop: 'remark',
    width: '90'
  }
]) as any
// 表一模块
const currentClickRow = ref()
const clickRow = (row: any = tableData.value[0]) => {
  currentClickRow.value = JSON.parse(JSON.stringify(row))
}
const currentTime = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1 // 月份从0开始，需要加1
  const day = now.getDate()
  const hour = now.getHours()
  const minute = now.getMinutes()
  return `${year}-${month}-${day} ${hour}:${minute}`
})
// 置空按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '查询') {
    getTableList()
  }
}
const findClicked2 = async (content: string) => {
  if (content === '分类辅助生成') {
    if (selectedList.value.length === 0) {
      JMessage.warning('请勾选通用材料订购明细')
      return
    }
    console.log(selectedList.value.some((item: any) => item.mtlNo === '' || item.mtlNo === null))

    // if (selectedList.value.some((item: any) => item.mtlNo === '' || item.mtlNo === null)) {
    //   JMessage.warning('请勾选有物料编码的通用材料订购明细')
    //   return
    // }
    let res = await LoginWork.post<any, any>(`/material/mtl/updateMaterialADetail1`, {
      choose: 1,
      list: selectedList.value
    })
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.warning(res.message)
    }
    getTableList()
  }
  if (content === '生成物料编码') {
    if (selectedList.value.length === 0) {
      JMessage.warning('请勾选通用材料订购明细')
      return
    }
    let res = await LoginWork.post<any, any>('/material/mtl/updateMaterialADetail1', {
      choose: 2,
      list: selectedList.value
    })
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.warning(res.message)
    }
    getTableList()
  }
  if (content === '置空物料编码') {
    if (selectedList.value.length === 0) {
      JMessage.warning('请勾选通用材料订购明细')
      return
    }
    let res = await LoginWork.post<any, any>('/material/mtl/updateMaterialADetail1', {
      choose: 3,
      list: selectedList.value
    })
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.warning(res.message)
    }
    getTableList()
  }
  if (content === '形成订购单') {
    let reg = formList2.value.find(
      (item: any) => item.type === 'select' && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '厂商代码 厂商名称'
    )?.selectValue
    let reg2 = formList2.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '交期'
    )?.dateValue
    if (!reg) JMessage.warning('厂商代码 厂商名称 不能为空')
    if (!reg2) JMessage.warning('交期 不能为空')
    if (!reg || !reg2) return
    if (selectedList.value.length === 0) {
      JMessage.warning('请勾选通用材料订购明细')
      return
    }
    let res = await LoginWork.post<any, any>('/material/mtl/updateMaterialADetail1', {
      choose: 4,
      deliveryDate: reg2,
      list: selectedList.value,
      vendorName: reg.split(' ')[1],
      vendorNo: reg.split(' ')[0]
    })
    if (res.code === 200) {
      JMessage.success(res.message)
      formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '已下单').checked = true
      setTimeout(async () => {
        await download()
      }, 1500)
    } else {
      JMessage.warning(res.message)
    }
    getTableList()
  }
  if (content === '导出订购单') {
    if (!currentClickRow.value.purNo) {
      JMessage.warning('没有订购单号')
      return
    }
    download()
  }
  if (content === '置空订购信息') {
    if (selectedList.value.length === 0) {
      JMessage.warning('请勾选通用材料订购明细')
      return
    }
    let res = await LoginWork.post<any, any>('/material/mtl/updateMaterialADetail1', {
      choose: 5,
      list: selectedList.value
    })
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.warning(res.message)
    }
    getTableList()
  }
  if (content === '打勾记录删除') {
    if (selectedList.value.length === 0) {
      JMessage.warning('请勾选通用材料订购明细')
      return
    }
    let res = await LoginWork.post<any, any>('/material/mtl/updateMaterialADetail1', {
      choose: 6,
      list: selectedList.value
    })
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.warning(res.message)
    }
    getTableList()
  }
  if (content === '>> 查询订购资料') {
    router.push('/Develop/RYDevelopment/ProductionPerformance')
  }
  if (content === '添加通用材料') {
    dialogTableVisible2.value = true
  }
}
const download = async () => {
  const res = (await fileRequest.get(`/material/downUniversalExcel?slipNo=${currentClickRow.value.purNo}`)) as any
  const link = document.createElement('a') // 利用a标签自定义下载文件名
  let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
  link.style.display = 'none'
  //设置连接
  link.href = window.URL.createObjectURL(blob)
  const FileName = decodeURI(res.headers['content-disposition'].split(`utf-8''`)[1])
  link.download = `${currentClickRow.value.vendorName} ${currentTime.value}.xls` //自定义文件名字
  document.body.appendChild(link)
  //模拟点击事件
  link.click()
  document.body.removeChild(link)
}
const tableData = ref([]) as any
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 表格计算函数
const cfmFlag = () => {
  const Unaudited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '未下单')
  const Audited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '已下单')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return 0
  } else if (Unaudited.checked) {
    return 1
  } else if (Audited.checked) {
    return 2
  } else {
    ElMessage('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return 0
  }
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>('/material/mtl/getMaterialADetail1', {
    mtlColor: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入材料颜色'
    )?.inputValue,
    mtlName: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入材料名称'
    )?.inputValue,
    purEndDate: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '订购日期'
    )?.dateValue?.[1],
    purNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入订购单号'
    )?.inputValue,
    purStartDate: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '订购日期'
    )?.dateValue?.[0],
    vendor: formList.value
      .find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '厂商代码 厂商名称')
      ?.selectValue?.split(' ')[1],
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    order: cfmFlag() //	下单
  })
  isLoading.value = false
  tableData.value = tableDataList.list.map((item: any) => {
    if (item.price) item.price = Number(item.price).toFixed(2)
    return item
  })
  total.value = tableDataList.total
  clickRow()
}, 500)
onMounted(() => {
  getTableList()
  getSelectList6()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)

// 表格选择数据
const selectedList = ref([])
const selectList1 = (selectList: any) => {
  selectedList.value = selectList
}
// 获取规格和单位下拉框数据
const getSelectList6 = async () => {
  const { specs, units } = await service.get<any, any>('/back/getMtlUS1')
  specs.map((Vendor: any) => {
    tableHeader.value
      .find((item: any) => item.label === '规格')
      .options.push({
        label: Vendor,
        value: Vendor
      })
  })
  units.map((Vendor: any) => {
    tableHeader.value
      .find((item: any) => item.label === '单位')
      .options.push({
        label: Vendor,
        value: Vendor
      })
  })
}
const getSelectList = async () => {
  let vendorName = await service.get<any, any>('/back/vendorQuery')
  let vendorNames = formList.value.find(
    (item: any) => item.type === 'select' && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '厂商代码 厂商名称'
  ) as any
  let vendorNames2 = formList2.value.find(
    (item: any) => item.type === 'select' && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '厂商代码 厂商名称'
  ) as any

  // 插入厂商代码 厂商名称
  if (vendorName && vendorNames) {
    vendorName.forEach((item: any, index: any) => {
      if (item === null) return
      vendorNames.selectOptions?.push({
        optionKey: index,
        optionValue: `${item.vendorNo} ${item.vendorName}`
      })
    })
  }
  // 插入厂商代码 厂商名称
  if (vendorName && vendorNames2) {
    vendorName.forEach((item: any, index: any) => {
      if (item === null) return
      vendorNames2.selectOptions?.push({
        optionKey: index,
        optionValue: `${item.vendorNo} ${item.vendorName}`
      })
    })
  }
}

// 获取分类名称下拉框数据
const getSelectList4 = async () => {
  const res = await service.get<any, any>('/back/getMtlType3')
  res.forEach((item: any) => {
    categoryNameOptions.value.push({
      label: `${item.typeName}`,
      value: `${item.typeNo}  ${item.typeName}`
    })
  })
}

// 获取材料名称下拉框数据
const getSelectList5 = async () => {
  const res2 = (await service.get<any, any>('/back/getMtlName3', {
    params: {
      mtlName: '',
      pageNum: 1,
      pageSize: 999999999
    }
  })) as any
  res2.list.map((Vendor: any, index: number) => {
    mtlNameOptions.value.push({
      value: `${Vendor.mtlNo}  ${Vendor.mtlName}  ${Vendor.mtlColor}  ${Vendor.mtlUnit}  ${Vendor.mtlSpec}`,
      label: `${Vendor.mtlColor}  ${Vendor.mtlName}  ${Vendor.mtlUnit}  ${Vendor.mtlSpec}  ${Vendor.mtlNo}`,
      LeftLabel: `${Vendor.mtlColor}  ${Vendor.mtlName}`,
      RightLabel: `${Vendor.mtlUnit}  ${Vendor.mtlSpec}  ${Vendor.mtlNo}`
    })
  })
}

onMounted(async () => {
  await getSelectList4()
  // await getSelectList5()
  await getSelectList()
})
const Save2 = async (arr: any, deleteArr: any) => {
  const res = (await LoginWork.post(`/material/mtl/updateMaterialADetail1`, {
    choose: 7,
    list: arr
      .filter((item: any) => item.mtlName)
      .map((item: any) => {
        if (item.typeName) {
          item.mtlTypeNo = item.typeName.split('  ')[0]
          item.typeName = item.typeName.split('  ')[1]
        }
        return item
      })
  })) as any
  // 判断请求是否成功
  if (res.code === 200) {
    JMessage.success(res.message)
    getTableList()
    deleteArr()
  } else {
    JMessage.warning(res.message)
  }
}
const AddHandle2 = (obj2: any, arr: any) => {
  obj2.purType = '通用'
  for (let index = 0; index < 5; index++) {
    const obj = {} as any
    for (const key in tableHeader.value) {
      obj[tableHeader.value[key].prop] = ''
    }
    obj.addAndUpdate = true
    obj.disableConfirm = true
    obj.purType = '通用'
    tableData.value.unshift(obj)
    arr.push(obj)
  }
}
// Dialog确认添加/修改按钮
const confirm = async (obj: any, dialogVisible: any, title: any) => {
  console.log(obj)
  // 打印出obj的值
  const tempList = formateData([obj]) as any
  // 向服务器发送请求，更新外派单信息
  if (title === '添加') {
    const obj2 = {} as any
    obj2.mtlColor = tempList[0].mtlName.split('  ')[2]
    obj2.mtlNo = tempList[0].mtlName.split('  ')[0]
    obj2.mtlName = tempList[0].mtlName.split('  ')[1]
    obj2.mtlUnit = tempList[0].mtlName.split('  ')[3]
    obj2.mtlSpec = tempList[0].mtlName.split('  ')[4]
    obj2.purType = '通用'
    obj2.typeName = obj.typeName.value.split('  ')[1]
    obj2.mtlTypeNo = obj.typeName.value.split('  ')[0]
    let res = await LoginWork.post<any, any>('/material/mtl/updateMaterialADetail1', {
      choose: 7,
      list: [
        {
          ...tempList[0],
          ...obj2
        }
      ]
    })
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.warning(res.message)
    }
    getTableList()
  }
  // 关闭弹出框
  dialogVisible.value = false
  // 重新获取表格数据
  getTableList()
}
</script>

<style lang="less" scoped>
:deep(.addFind) {
  .inputBase {
    width: 150px;
  }
}

:deep(.el-form-item:nth-child(2)) {
  .el-select {
    width: 150px;
    height: 28px;
  }
}

:deep(.el-form-item:nth-last-child(8)) {
  .el-select {
    width: 150px;
    height: 28px;
  }
}
</style>
